<template>
  <view class="vipcard-container">
    <!-- 卡片图片 -->
    <!-- <view class="card-preview">
            <image class="card-image" :src="cardInfo.icon" mode="aspectFill"></image>
        </view> -->

    <!-- 卡片名称 -->
    <!-- <view class="card-header" >
            <text class="card-title">{{ cardInfo.card_name || cardInfo.name }}</text>
        </view> -->

    <view class="card-top">
      <view class="card-background">
        <image class="bg-image" :src="cardInfo.image" mode="aspectFill"></image>
      </view>

      <!-- VIP卡片 -->
      <view class="vip-card">
        <image
          class="card-image"
          :src="cardInfo.image"
          mode="aspectFill"
        ></image>
      </view>

      <!-- 按钮组 -->
      <view class="button-group" v-if="cardInfo.mid == mid">
        <button
          :style="{ background: t('color1') }"
          class="btn btn-primary"
          @tap="handleRecharge"
        >
          充值
        </button>
        <button
          :style="{ background: t('color1') }"
          class="btn btn-primary"
          @tap="handleChangePassword"
        >
          修改密码
        </button>
      </view>
    </view>

    <!-- 卡片说明 -->
    <view class="card-description" v-if="false">
      <view class="section-title">
        <image
          class="icon"
          :src="static_url + '/static/img/vip.png'"
          mode="aspectFit"
        ></image>
        <text>会员卡说明</text>
      </view>
      <view class="description-content">
        <text class="desc-text">{{ cardInfo.describe }}</text>
        <!-- <view class="benefit-list">
                    <view class="benefit-item">
                        <image class="benefit-icon" :src="static_url + '/static/img/vip.png'" mode="aspectFit"></image>
                        <text>全场9折优惠</text>
                    </view>
                    <view class="benefit-item">
                        <image class="benefit-icon" :src="static_url + '/static/img/vip.png'" mode="aspectFit"></image>
                        <text>积分兑换礼品</text>
                    </view>
                    <view class="benefit-item">
                        <image class="benefit-icon" :src="static_url + '/static/img/vip.png'" mode="aspectFit"></image>
                        <text>生日特权礼遇</text>
                    </view>
                </view> -->
      </view>
    </view>

    <!-- 卡片信息 -->
    <view class="card-info">
      <view class="section-title">
        <image
          class="icon"
          :src="static_url + '/static/img/vip.png'"
          mode="aspectFit"
        ></image>
        <text>会员卡信息</text>
      </view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">卡类型</text>
          <text class="value">{{ cardInfo.card_name }}</text>
        </view>
        <view class="info-item">
          <text class="label">卡号</text>
          <text class="value">{{ cardInfo.card_num }}</text>
        </view>
        <view class="info-item">
          <text class="label">折扣</text>
          <!-- <text class="value">{{ (cardInfo.discount * 100) / 10 }}</text> -->
          <text class="value">{{ cardInfo.discount }}</text>
        </view>
        <view class="info-item">
          <text class="label">开卡人</text>
          <text class="value">{{ cardInfo.member_nickname }}</text>
        </view>
        <view class="info-item">
          <text class="label">开卡人手机号</text>
          <text class="value">{{ cardInfo.member_tel }}</text>
        </view>
        <view class="info-item">
          <text class="label">持卡人</text>
          <text class="value">{{ cardInfo.bind_member_nickname }}</text>
        </view>
        <view class="info-item">
          <text class="label">持卡人手机号</text>
          <text class="value">{{ cardInfo.bind_member_tel }}</text>
        </view>
        <view class="info-item">
          <text class="label">余额</text>
          <text class="value">{{ cardInfo.money }}</text>
        </view>
        <view class="info-item">
          <text class="label">开卡时间</text>
          <text class="value">{{ cardInfo.createtime }}</text>
        </view>
        <view
          class="info-item"
          v-if="cardInfo.use_time_end && cardInfo.bind_mid != 0"
        >
          <text class="label">使用时间</text>
          <text class="value">
            {{ cardInfo.use_time_start.substring(0, 10) }}~{{
              cardInfo.use_time_end.substring(0, 10)
            }}</text
          >
        </view>
        <!-- <view class="info-item">
                    <text class="label">累计充值</text>
                    <text class="value">{{ cardInfo.accumulate_money }}</text>
                </view> -->
        <!-- <view class="info-item">
                    <text class="label">消费记录</text>
                    <text class="value">></text>
                </view> -->
      </view>
    </view>

    <!-- 底部操作按钮  -->
    <view class="bottom-actions">
      <view class="action-btn-group1">
        <button
          :style="{ background: t('color1') }"
          class="action-btn secondary"
          @tap="handleUnbind"
          v-if="cardInfo.bind_mid != 0"
        >
          解绑此卡
        </button>
        <!-- <button class="action-btn outline" @tap="handleChangePassword" v-if="cardInfo.mid == mid">修改密码</button> -->
        <!-- <button :style="{ background: t('color1') }" open-type="share" class="action-btn  primary"
					@tap="handleGive" v-if="allowShare && cardInfo.mid == mid && cardInfo.bind_mid == 0">转赠他人</button> -->
        <button
          :style="{ background: t('color1') }"
          class="action-btn primary"
          @tap="handleGive"
          v-if="allowShare && cardInfo.mid == mid && cardInfo.bind_mid == 0"
        >
          转赠他人
        </button>
        <button
          :style="{ background: t('color1') }"
          class="action-btn primary"
          @tap="handleGive"
          v-if="!allowShare && cardInfo.mid == mid && cardInfo.bind_mid == 0"
        >
          转赠他人
        </button>
        <!-- v-if="cardInfo.mid == mid" -->
        <!-- <button class="action-btn primary" @tap="handleRecharge">充值</button> -->
        <!-- <button class="action-btn primary" @tap="test">test</button> -->
      </view>
    </view>

    <uni-popup id="dialogInput" ref="dialogInput" type="dialog">
      <uni-popup-dialog
        mode="input"
        :title="poptitle"
        value=""
        :placeholder="popplaceholder"
        @confirm="getpwd"
        password="true"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup id="dialogInput2" ref="dialogInput2" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="充值金额"
        value=""
        placeholder="请输入充值金额"
        @confirm="getRecharge"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup id="dialogInput3" ref="dialogInput3" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="购买金额"
        value=""
        placeholder="请输入购买金额"
        @confirm="getbuy"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="rulePopup" type="center" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title">请选择使用条件</view>
        <radio-group @change="radioChange">
          <label class="radio-item">
            <view class="radio-content">
              <radio
                value="1"
                :checked="conditionType === '1'"
                color="#007AFF"
              />
              <text>无限制使用条件</text>
            </view>
          </label>
          <label class="radio-item">
            <view class="radio-content">
              <radio
                value="2"
                :checked="conditionType === '2'"
                color="#007AFF"
              />
              <text>限制使用日期</text>
            </view>
            <view v-if="conditionType === '2'" class="date-range">
              <view class="date-picker-item">
                <text class="date-label">开始时间：</text>
                <picker
                  mode="date"
                  :value="startDate"
                  @change="startDateChange"
                  :start="minDate"
                  :end="maxDate"
                >
                  <view class="date-text"
                    >{{
                      startDate
                        ? formatFullStartDate(startDate)
                        : "请选择开始日期"
                    }}
                  </view>
                </picker>
              </view>
              <view class="date-picker-item">
                <text class="date-label">结束时间：</text>
                <picker
                  mode="date"
                  :value="endDate"
                  @change="endDateChange"
                  :start="startDate || minDate"
                  :end="maxDate"
                >
                  <view class="date-text">{{
                    endDate ? formatFullEndDate(endDate) : "请选择结束日期"
                  }}</view>
                </picker>
              </view>
            </view>
          </label>
        </radio-group>
        <view class="popup-buttons">
          <button @click="closePopup">取消</button>
          <button
            type="primary"
            open-type="share"
            @click="confirmCondition"
            :style="{ background: t('color1') }"
          >
            确定
          </button>
        </view>
      </view>
    </uni-popup>
    <loading v-if="loading"></loading>
  </view>
</template>

<script>
var app = getApp();
export default {
  data() {
    const today = this.formatDate(new Date());
    const nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear() + 1);
    const maxDate = this.formatDate(nextYear);
    return {
      mid: 0,
      loading: false,
      allowShare: false, // 是否允许分享
      cardInfo: {
        // "id": 6,
        // "aid": 3,
        // "mid": 419,
        // "vip_card_config_id": 3,
        // card_name: "普通卡",
        // "card_num": "VIP25021715520338951",
        // "password": "111",
        // "money": "1.00",
        // "bind_mid": 0,
        // "status": 0,
        // "accumulate_money": "1.00",
        // "createtime": 1739778723,
        // "updatetime": 1739778723,
        // "bind_time": 0,
        // "unbind_time": 0,
        // card_desc: '普通卡普通卡普通卡普通卡',
        // bgImg: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250217/c3da2db730225037d00dab6bdb8d3fb5.jpg'
      },
      id: 0,
      share_title: "",
      share_path: "",
      share_imageUrl: "",
      pre_url: app.globalData.pre_url,
      static_url: app.globalData.static_url,
      conditionType: "1",
      minDate: today,
      maxDate: maxDate,
      startDate: "",
      endDate: "",
      poptitle: "修改密码",
      popplaceholder: "请输入支付密码",
    };
  },
  onLoad(options) {
    this.mid = app.globalData.mid;
    this.id = options.id;
    this.getdata();
  },
  onPullDownRefresh: function () {
    this.getdata();
  },
  methods: {
    getdata() {
      let that = this;
      app.showLoading("加载中");
      app.get(
        "MemberVipCard/cardInfo?member_vip_card_id=" + that.id,
        {},
        function (res) {
          if (res && res.status == 200) {
            that.cardInfo = res.data;
            if (that.cardInfo.password != "") {
              that.allowShare = true;
            }
            if (that.mid == that.cardInfo.mid) {
              that.getShare2();
            }
            app.showLoading(false);
          } else {
            app.showLoading(false);
            app.error(res.msg);
          }
          that.loaded();
        }
      );
    },

    test() {},

    handleRecharge() {
      this.$refs.dialogInput2.open();
    },

    handleUnbind() {
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确定要解绑该卡片吗？",
        success: (res) => {
          if (res.confirm) {
            app.showLoading("解绑中");
            app.post(
              "MemberVipCard/unBind",
              {
                member_vip_card_id: that.id,
              },
              function (res) {
                if (res.status == 200) {
                  app.showLoading(false);
                  app.success("解绑成功");
                  setTimeout(() => {
                    uni.navigateBack();
                  }, 1000);
                } else {
                  app.showLoading(false);
                  app.error(res.msg);
                }
              }
            );
          }
        },
      });
    },

    getShare() {
      let that = this;
      that.loading = true;

      // 准备请求数据
      let requestData = {
        member_vip_card_id: that.id,
        bind_use_type: that.conditionType,
      };

      // 如果是限制使用日期，添加日期参数
      if (that.conditionType === "2") {
        if (!that.startDate || !that.endDate) {
          uni.showToast({
            title: "请选择完整的使用日期",
            icon: "none",
          });
          that.loading = false;
          return;
        }
        requestData.use_time_start = that.startDate + " 00:00:00";
        requestData.use_time_end = that.endDate + " 23:59:59";
      }

      app.post("MemberVipCard/gift", requestData, function (res) {
        that.loading = false;
        if (res.status == 200) {
          that.share_title = res.data.title;
          that.share_path = res.data.url;
          that.share_imageUrl = res.data.pic;

          // 显示分享弹窗或其他操作
          that.showSharePopup();
        } else {
          uni.showToast({
            title: res.msg || "获取分享信息失败",
            icon: "none",
          });
        }
      });
    },

    getShare2() {
      let that = this;
      that.loading = true;
      // 准备请求数据
      let requestData = {
        member_vip_card_id: that.id,
        bind_use_type: "1",
      };

      app.post("MemberVipCard/gift", requestData, function (res) {
        that.loading = false;
        if (res.status == 200) {
          that.share_title = res.data.title;
          that.share_path = res.data.url;
          that.share_imageUrl = res.data.pic;
        } else {
        }
      });
    },

    handleGive() {
      let that = this;
      //console.log(that.cardInfo.password);
      //console.log(this.share_title, this.share_path, this.share_imageUrl);

      if (that.cardInfo.password == "") {
        // app.error('请先设置密码');
        that.checkPassword();
        return;
      }

      // if (this.share_title == '' && this.share_path == '' && this.share_imageUrl == '') {
      // 	app.error('分享信息未设置');
      // 	return;
      // }

      if (that.cardInfo.password != "") {
        this.$refs.rulePopup.open();
        // that.allowShare = true; // 允许分享
        // uni.share({
        //     title: that.share_title,
        //     path: that.share_path,
        //     imageUrl: that.share_imageUrl,
        // });
      } else {
        that.allowShare = false; // 禁止分享
        app.error("请先设置密码");
      }
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 格式化为开始时间 YYYY-MM-DD 00:00:00
    formatFullStartDate(date) {
      return `${date} 00:00:00`;
    },

    // 格式化为结束时间 YYYY-MM-DD 23:59:59
    formatFullEndDate(date) {
      return `${date} 23:59:59`;
    },

    openConditionPopup() {
      this.$refs.rulePopup.open();
    },

    closePopup() {
      this.$refs.rulePopup.close();
    },

    radioChange(e) {
      this.conditionType = e.detail.value;
    },

    startDateChange(e) {
      this.startDate = e.detail.value;
      if (this.endDate && this.endDate < this.startDate) {
        this.endDate = "";
      }
    },

    endDateChange(e) {
      this.endDate = e.detail.value;
    },

    confirmCondition() {
      let requestData = {
        condition_type: this.conditionType,
      };

      if (this.conditionType === "2") {
        if (!this.startDate) {
          uni.showToast({
            title: "请选择开始日期",
            icon: "none",
          });
          return;
        }
        if (!this.endDate) {
          uni.showToast({
            title: "请选择结束日期",
            icon: "none",
          });
          return;
        }
        if (this.startDate > this.endDate) {
          uni.showToast({
            title: "结束日期不能早于开始日期",
            icon: "none",
          });
          return;
        }

        // 添加日期时间数据
        requestData.start_time = this.startDate + " 00:00:00";
        requestData.end_time = this.endDate + " 23:59:59";
      }

      // 提交数据到后端
      this.getShare();
      this.closePopup();
    },

    checkPassword() {
      let that = this;
      that.poptitle = "转赠提示";
      that.popplaceholder = "请先设置支付密码";
      that.$refs.dialogInput.open();
      // uni.showModal({
      //   title: "提示",
      //   content: "请先设置密码后再分享",
      //   success(res) {
      //     if (res.confirm) {
      //       that.$refs.dialogInput.open();
      //     } else if (res.cancel) {
      //     }
      //   },
      // });
    },

    handleChangePassword() {
      let that = this;
      that.poptitle = "修改密码";
      that.popplaceholder = "请输入支付密码";
      if (that.cardInfo.password != "") {
        uni.showModal({
          title: "提示",
          content: "密码已经设置，是否确认重置？",
          success(res) {
            if (res.confirm) {
              that.$refs.dialogInput.open();
            } else if (res.cancel) {
            }
          },
        });
      } else {
        that.$refs.dialogInput.open();
      }
    },

    getpwd: function (done, val) {
      let that = this;
      let paypwd = val;
      if (paypwd == "") {
        app.error("密码不能为空");
        return;
      }
      app.showLoading("修改中");
      app.post(
        "MemberVipCard/setCardPassword",
        {
          member_vip_card_id: that.id,
          password: paypwd,
        },
        function (res) {
          if (res && res.status == 200) {
            app.showLoading(false);
            that.$refs.dialogInput.close();
            app.success("修改成功");
            setTimeout(() => {
              that.getdata();
            }, 1000);
          } else {
            app.showLoading(false);
            app.error(res.msg);
          }
        }
      );
    },

    getRecharge(done, val) {
      var that = this;
      if (val == "") {
        app.error("金额不能为空");
        return;
      }
      that.loading = true;
      app.post(
        "MemberVipCard/recharge",
        {
          money: val,
          member_vip_card_id: that.cardInfo.id,
        },
        function (res) {
          that.loading = false;
          if (res.status == 200) {
            app.goto("/pages/pay/pay?id=" + res.payorderid);
          } else {
            app.error(res.msg);
          }
        }
      );
    },
    getbuy(done, val) {
      var that = this;
      if (val == "") {
        app.error("金额不能为空");
        return;
      }
      that.buyCard(val);
    },
  },
  onShareAppMessage() {
    return {
      title: this.share_title,
      path: this.share_path,
      imageUrl: this.share_imageUrl,
    };
  },
};
</script>

<style lang="scss">
.vipcard-container {
  min-height: 100vh;
  background: #fff;
  padding-bottom: 180rpx;

  .card-top {
    padding: 80rpx;
    padding-bottom: 0;

    .card-background {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 600rpx;
      overflow: hidden;

      .bg-image {
        width: 100%;
        height: 100%;
        filter: blur(20px);
        transform: scale(1.1);
        opacity: 0.8;
      }
    }

    .vip-card {
      position: relative;
      border-radius: 30rpx;
      overflow: hidden;
      // background: #fff;
      //box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      box-shadow: 0px 5px 10px 2px rgba(0, 0, 0, 0.2);

      .card-image {
        width: 100%;
        height: 350rpx;
        display: block;
      }

      .card-content {
        position: absolute;
        top: 40rpx;
        left: 40rpx;
        right: 40rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .card-title {
          color: #fff;
          font-size: 32rpx;
        }

        .card-vip {
          color: #fff;
          font-size: 36rpx;
        }
      }
    }

    .button-group {
      display: flex;
      margin-top: 20rpx;
      padding-top: 20rpx;
      padding-bottom: 20rpx;

      gap: 40rpx;

      .btn {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background: #8b0000;
        color: #fff;
        border-radius: 8rpx;
        font-size: 28rpx;
        border-radius: 44rpx;
      }
    }
  }

  .card-header {
    background: #fff;
    padding: 30rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;

    .card-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .card-preview {
    width: 100%;
    height: 250rpx;
    overflow: hidden;

    .card-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    padding: 30rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;

    .icon {
      width: 45rpx;
      height: 45rpx;
      margin-right: 16rpx;
    }
  }

  .card-description {
    background: #fff;
    margin-top: 20rpx;

    .description-content {
      padding: 0 30rpx 30rpx;

      .desc-text {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 30rpx;
      }

      .benefit-list {
        display: flex;
        flex-wrap: wrap;

        .benefit-item {
          display: flex;
          align-items: center;
          width: 50%;
          margin-bottom: 20rpx;

          .benefit-icon {
            width: 36rpx;
            height: 36rpx;
            margin-right: 10rpx;
          }

          text {
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    }
  }

  .card-info {
    background: #fff;
    margin-top: 20rpx;
    z-index: 9;
    position: relative;

    .info-list {
      padding: 0 30rpx;

      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .label {
          font-size: 28rpx;
          color: #666;
        }

        .value {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
  }

  .bottom-actions {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background: #fff;
    // box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    z-index: 9;

    .action-btn {
      width: 320rpx;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 32rpx;
      border-radius: 44rpx;
      margin: 0;

      &.primary {
        background: #8b0000;
        color: #fff;
      }

      &.outline {
        background: #fff;
        color: #666;
        border: 2rpx solid #ddd;
      }

      &.secondary {
        background: #ffedc6;
        color: #fff;
      }

      &::after {
        border: none;
      }
    }
  }
}

.action-btn-group1 {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn-group2 {
  display: flex;
  justify-content: space-between;

  .card-balance,
  .card-price {
    .label,
    .price-label {
      font-size: 28rpx;
      opacity: 0.9;
    }

    .amount,
    .price-amount {
      font-size: 48rpx;
      font-weight: bold;
      margin-left: 20rpx;
    }
  }
}

.popup-content {
  width: 85vw;
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-sizing: border-box;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.radio-item {
  display: flex;
  flex-direction: column;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.radio-content {
  display: flex;
  align-items: center;
}

.radio-content text {
  margin-left: 20rpx;
}

.date-range {
  margin-top: 20rpx;
  margin-left: 60rpx;
}

.date-picker-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.date-label {
  // width: 120rpx;
  font-size: 28rpx;
}

.date-text {
  color: #007aff;
  padding: 10rpx 20rpx;
  border: 1rpx solid #007aff;
  border-radius: 8rpx;
  display: inline-block;
}

.popup-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.popup-buttons button {
  width: 48%;
}
</style>
